<template>
  <div class="main">
    <h3 class="title">STUDENT INFO MANAGE</h3>
    <div class="search">
      <el-card>
        <div slot="header">
          <span>条件查询</span>
        </div>
        <div class="search-container">
          <el-row :gutter="10" type="flex" justify="center">
            <el-col :span="2">
              <label for="search-name">姓名:</label>
            </el-col>
            <el-col :span="4">
              <el-input
                id="search-name"
                v-model="student.name"
                clearable
                placeholder="请输入内容"
              />
            </el-col>
            <el-col :span="2" :offset="2">
              <label for="search-dorm">宿舍:</label>
            </el-col>
            <el-col :span="6">
              <el-select v-model="student.dormId" clearable placeholder="">
                <el-option
                  v-for="item in dormList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col :span="2">
              <label for="search-class">班级:</label>
            </el-col>
            <el-col :span="6">
              <el-select v-model="student.classId" clearable placeholder="">
                <el-option
                  v-for="item in classList"
                  :key="item.id"
                  :label="item.className"
                  :value="item.id"
                />
              </el-select>
            </el-col>
          </el-row>

          <el-row :gutter="10" style="margin-top: 10px">
            <el-col :span="2">
              <label for="search-startTime">开始日期:</label>
            </el-col>
            <el-col :span="6">
              <el-date-picker
                v-model="student.startTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-col>
            <el-col :span="2">
              <label for="search-endTime">结束日期:</label>
            </el-col>
            <el-col :span="6">
              <el-date-picker
                v-model="student.endTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-col>
            <el-col :span="2">
              <label for="search-status">学习阶段:</label>
            </el-col>
            <el-col :span="6">
              <el-select v-model="student.status" clearable placeholder="">
                <el-option
                  label="在学"
                  :value="0"
                />
                <el-option
                  label="找工作"
                  :value="1"
                />
                <el-option
                  label="已工作"
                  :value="2"
                />
              </el-select>

            </el-col>
          </el-row>

          <el-row :gutter="20" type="flex" justify="center" style="margin-top: 20px">
            <el-col :span="3" :offset="9">
              <el-button
                class="search-btn"
                @click="clear"
              >clear</el-button>
            </el-col>
            <el-col :span="3">
              <el-button
                class="search-btn"
                @click="askAddStudent"
              >新增学员</el-button>
            </el-col>
            <el-col :span="3">
              <el-button
                type="danger"
                class="search-btn"
                @click="mock"
              >mock</el-button>
            </el-col>
            <el-col :span="3">
              <el-button
                type="primary"
                class="search-btn"
                @click="search"
              >查询</el-button>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
    <el-card>
      <div slot="header">
        <span>学生信息</span>
      </div>
      <!-- card body -->
      <el-table :data="studentList" style="width: 100%">
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="addTime" label="日期" width="180" />
        <el-table-column prop="name" label="姓名" width="180" />
        <el-table-column prop="sexv" label="性別" width="180" />
        <el-table-column prop="dormname" label="宿舍" />
        <el-table-column prop="classname" label="班级" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="askEdit(scope.$index, scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="askDelete(scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px; text-align:center"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog title="提示" :visible.sync="dialog.delVisible" width="30%">
      <span>是否确认删除</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.delVisible = false">取 消</el-button>
        <el-button type="primary" @click="doDelete">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :before-close="handleCloseEdit" title="学生信息" :visible.sync="dialog.formVisible" width="80%">
      <el-form :model="studentForm">
        <div class="sub-title">基本信息</div>
        <el-divider />
        <el-row :gutter="20" type="flex" justify="space-around">
          <el-col :span="6">
            <el-form-item label="姓名" :label-width="formLabelWidth" required>
              <el-input v-model="studentForm.name" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" :label-width="formLabelWidth" required>
              <el-select v-model="studentForm.sex" placeholder="">
                <el-option label="女" value="1" />
                <el-option label="男" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="班级" :label-width="formLabelWidth" required>
              <el-select v-model="studentForm.classId" placeholder="">
                <el-option
                  v-for="item in classList"
                  :key="item.id"
                  :label="item.className"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="space-around">
          <el-col :span="6">
            <el-form-item label="电话" :label-width="formLabelWidth" required>
              <el-input v-model="studentForm.tel" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证" :label-width="formLabelWidth">
              <el-input v-model="studentForm.manID" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市" :label-width="formLabelWidth">
              <el-cascader
                v-model="studentForm.city"
                size="small"
                :options="options"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="space-around">
          <el-col :span="6">
            <el-form-item label="宿舍" :label-width="formLabelWidth" required>
              <el-select v-model="studentForm.dormId" placeholder="">
                <el-option
                  v-for="item in dormList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入住日期" :label-width="formLabelWidth">
              <el-date-picker
                v-model="studentForm.dormStartTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="离开日期" :label-width="formLabelWidth">
              <el-date-picker
                v-model="studentForm.dormEndTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="sub-title" style="margin-top: 20px">补充信息</div>
        <el-divider />
        <el-row :gutter="20" type="flex" justify="space-around">
          <el-col :span="6">
            <el-form-item label="紧急联系人" label-width="90px">
              <el-input v-model="studentForm.tel2" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="微信" :label-width="formLabelWidth">
              <el-input v-model="studentForm.wx" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="QQ" :label-width="formLabelWidth">
              <el-input v-model="studentForm.qq" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" type="flex" justify="space-around">
          <el-col :span="6">
            <el-form-item label="毕业院校" :label-width="formLabelWidth">
              <el-input v-model="studentForm.school" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工作" :label-width="formLabelWidth">
              <el-input v-model="studentForm.job" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="6" />
        </el-row>
        <div class="sub-title" style="margin-top: 20px">交费信息</div>
        <el-divider />
        <el-card style="width: 90%" shadow="never">
          <el-row>
            <el-col>
              <el-form-item label="交费类型 " :label-width="formLabelWidth">
                <el-radio-group v-model="costForm.costType" size="mini">
                  <el-radio-button label="0">学费</el-radio-button>
                  <el-radio-button label="1">住宿费</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="交费金额" :label-width="formLabelWidth">
                <el-input v-model="costForm.costValue" autocomplete="off" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="交费时间" :label-width="formLabelWidth">
              <el-date-picker
                v-model="costForm.costTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="备注" :label-width="formLabelWidth">
                <el-input
                  v-model="costForm.costBak"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" :offset="1">
              <el-button @click="clearCost">清  空</el-button>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" @click="addCost">添加交费记录</el-button>
            </el-col>
          </el-row>
        </el-card>
        <el-table :data="costListC" :stripe="true" border style="margin-top: 20px">
          <el-table-column type="index" label="#" width="50" />
          <el-table-column prop="costType" label="类型" width="180" />
          <el-table-column prop="costValue" label="金额" width="180" />
          <el-table-column prop="costTime" label="时间" width="180" />
          <el-table-column prop="costBak" label="备注" />
          <el-table-column label="操作" width="60">
            <template slot-scope="scope">
              <el-button
                v-if="costListC[scope.$index].del"
                type="text"
                @click="deleteTempCost(scope.$index)"
              >删除</el-button></template>
          </el-table-column>
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 20px" @click="handleCloseEdit">取 消</el-button>
        <el-button type="primary" @click="doPost">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStudentList,
  delStudent,
  addStudent,
  updateStudent,
  getStudentInfo,
  getCostList
} from '@/api/student'
import { getDormList } from '@/api/dorm'
import { getClassList } from '@/api/class'
import _ from 'lodash'
import { regionData } from 'element-china-area-data'
var Mock = require('mockjs')

export default {
  data() {
    return {
      studentList: [],
      dormList: [],
      classList: [],
      selectedIndex: 0,
      student: {
        name: '',
        classId: '',
        dormId: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      studentForm: {
        name: '',
        sex: '',
        classId: '',
        dormId: '',
        status: '',
        startTime: '',
        endTime: '',
        dormStartTime: '',
        dormEndTime: '',
        job: '',
        wx: '',
        qq: '',
        school: '',
        city: ''
      },
      costForm: {
        costType: 0,
        costValue: '',
        costTime: '',
        costBak: ''
      },
      costPredictList: [],
      costList: [],
      // pagination setting
      pagination: {
        limit: 10,
        current: 1,
        total: 0
      },
      // dialog
      dialog: {
        delVisible: false,
        formVisible: false
      },
      // city cascader
      options: regionData,
      selectedOptions: [],
      formLabelWidth: '80px'
    }
  },
  computed: {
    costListC() {
      return this.costList.map(el => {
        if (el.costType === 0) {
          el.costType = '学费'
        } else {
          el.costType = '住宿费'
        }

        return el
      })
    }
  },
  created() {
    this.setStudentList()
    this.setClassList()
    this.setDormList()
  },
  methods: {
    setStudentList() {
      let params = this.student
      params = _.pickBy(params, item => item)
      getStudentList({
        start: this.pagination.current,
        limit: this.pagination.limit,
        ...params
      }).then(res => {
        this.studentList = res.data.list
        this.pagination.total = res.data.totalRow
      }).catch(res => {
        this.$message.error(res)
      })
    },
    setDormList() {
      getDormList({
        start: 1,
        limit: 28
      }).then(res => {
        this.dormList = res.data.list
      }).catch(res => {
        this.$message.error(res)
      })
    },
    setClassList() {
      getClassList({
        start: 1,
        limit: 18
      }).then(res => {
        this.classList = res.data.list
      }).catch(res => {
        this.$message.error(res)
      })
    },
    setCostList() {
      return getCostList({
        userId: this.studentList[this.selectedIndex].id
      })
    },
    search() {
      this.pagination.current = 1
      this.limit = 10
      this.setStudentList()
    },
    handleSizeChange(val) {
      this.pagination.limit = val
      this.pagination.current = 1
      this.setStudentList()
    },
    handleCurrentChange(val) {
      this.pagination.current = val
      this.setStudentList()
    },
    handleCloseEdit() {
      this.dialog.formVisible = false
      this.costPredictList = []
      this.studentForm = this.$options.data().studentForm
      this.costList = []
    },
    askAddStudent() {
      this.dialog.formVisible = true
    },
    async askEdit(index, sid) {
      this.selectedIndex = index
      const res = await this.setCostList()
      this.costList = res.data.list

      getStudentInfo({
        id: this.studentList[index].id
      }).then(res => {
        this.studentForm = res.data
        // edit city paramters, turn String => Array, make the city cascader work
        if (this.studentForm.city !== null) {
          this.studentForm.city = this.studentForm.city.split(',')
        }
      })

      this.dialog.formVisible = true
    },
    async doPost() {
      // turn city parameter from Array to String
      if (this.studentForm.city !== null) {
        this.studentForm.city = this.studentForm.city.join(',')
      }
      // push the new student info if the student id exist, or update the info
      let api = null
      let postObj = {}

      postObj = {
        xyUser: {
          ...this.studentForm
        },
        _size: this.costPredictList.length
      }
      for (let i = 0; i < this.costPredictList.length; i++) {
        postObj[`xyCostItems_${i}`] = this.costPredictList[i]
      }

      if (this.studentForm.id !== undefined) {
        api = updateStudent
      } else {
        api = addStudent
      }

      const res = await api(postObj)

      if (res.code === 'success') {
        this.$message.success('保存成功!')
      } else {
        this.$message.error('保存失败!')
      }

      this.dialog.formVisible = false
      this.handleCloseEdit()
      this.setStudentList()
    },
    askDelete(index) {
      this.dialog.delVisible = true
      this.selectedIndex = index
    },
    doDelete() {
      delStudent({
        id: this.studentList[this.selectedIndex].id
      })

      this.dialog.delVisible = false
      this.setStudentList()
    },
    clear() {
      this.student = this.$options.data().student
    },
    clearCost() {
      this.costForm = this.$options.data().costForm
    },
    addCost() {
      const costInstance = _.cloneDeep(this.costForm)
      const costInstanceTemp = _.cloneDeep(this.costForm)

      costInstanceTemp.del = true
      this.costList.push(costInstanceTemp)
      this.costPredictList.push(costInstance)
      this.costForm = this.$options.data().costForm
    },
    deleteTempCost(index) {
      this.costList.splice(index, 1)
    },
    mock() {
      const Random = Mock.Random
      const stuList = []

      for (let i = 0; i < 1; i++) {
        const stu = {
          name: Random.cword(2, 3),
          sex: 0,
          manID: Random.id(),
          tel: Random.integer(10000000000, 19999999999),
          city: '120000,120100,120101',
          cityText: Random.county(true).split(' ').join(','),
          classId: Random.pick(this.classList.map(el => el.id)),
          dormId: Random.pick(this.dormList.map(el => el.id)),
          school: Random.cword(3, 10),
          job: Random.cword(3, 5),
          dormStartTime: Random.date('yyyy-MM-dd'),
          dormEndTime: Random.date('yyyy-MM-dd'),
          qq: Random.integer(100000, 99999999),
          wx: Random.word(6, 10),
          classname: Random.cword(3),
          dormname: Random.cword(3),
          age: Random.integer(18, 30),
          tel2: Random.integer(10000000000, 19999999999)
        }
        const xyCostItems_0 = {
          costType: 0,
          costTime: Random.date('yyyy-MM-dd'),
          costValue: Random.integer(100000, 99999999),
          costBak: Random.csentence()
        }
        const xyCostItems_1 = {
          costType: 1,
          costTime: Random.date('yyyy-MM-dd'),
          costValue: Random.integer(100000, 99999999),
          costBak: Random.csentence()
        }

        stuList.push(stu)
        addStudent({
          xyUser: {
            ...stuList[i]
          },
          _size: 2,
          xyCostItems_0,
          xyCostItems_1
        })
      }

      this.setStudentList()
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  margin: 0 auto;
  .title {
    text-align: center;
    font-weight: normal;
  }

  .el-card {
    width: 1200px;
    margin: 0 auto;
  }

  .search {
    height: 100%;
    .search-container {
      margin-right: -50px;
    }
    label {
      display: block;
      width: 100%;
      height: 100%;
      font-weight: normal;
      line-height: 40px;
      text-align: center;
    }

    .search-btn {
      width: 100%;
      margin-top: 10px;
    }
  }
}
</style>
